package it.orma.iridehr.controllers;

import javax.servlet.http.HttpServletResponse;

import it.orma.iridehr.service.AlfrescoService;
import it.orma.iridehr.services.helper.DocumentoAlfresco;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

@Component
@Scope("prototype")
public class LeggiDocumentoAlfresco extends AbstractAction {
	
	@Autowired
	private AlfrescoService alfrescoService;
	
	@Override
	protected Event doExecute(RequestContext context) throws Exception {
		String idDocumento = context.getRequestParameters().get("idDocumento");
		HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getNativeResponse();
		DocumentoAlfresco doc = alfrescoService.estraiTestoDalDocumento(idDocumento);
		response.setContentLength(new Long(doc.getContentLenght()).intValue());
		response.setContentType(doc.getContentType());
		response.setHeader("Content-Disposition", "attachment; filename="+doc.getFileName());
		IOUtils.copy(doc.getStream(), response.getOutputStream());
		response.getOutputStream().close();
		context.getExternalContext().recordResponseComplete();
		return null;
	}

}
